import { ref, onMounted, onUnmounted } from "vue";

// 格式化时间函数
const formatTime = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
};
// 格式化时间-返回年月日
const formatTimeHasDay = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}/${month}/${day}`;
};
// 格式化时间-返回3天后的年月日
const getThreeDaysLaterFormatted = () => {
  const now = new Date();
  const threeDaysLater = new Date(now);
  threeDaysLater.setDate(now.getDate() + 3);
  return formatTimeHasDay(threeDaysLater);
};

// 时间处理 Hook
export function useTime(updateInterval = 1000) {
  // 本地时间和 UTC 时间的响应式变量
  const localTime = ref("");
  const utcTime = ref("");
  let timer = null;

  // 更新时间的函数
  const updateTime = () => {
    const now = new Date();

    formatTimeHasDay(now);

    // 更新本地时间
    localTime.value = formatTime(now);

    // 计算并更新 UTC 时间
    const utcNow = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
    utcTime.value = formatTime(utcNow);
  };

  // 组件挂载时初始化时间并启动定时器
  onMounted(() => {
    updateTime(); // 立即更新一次
    timer = setInterval(updateTime, updateInterval);
  });

  // 组件卸载时清除定时器
  onUnmounted(() => {
    if (timer) {
      clearInterval(timer);
    }
  });

  // 返回响应式时间和格式化函数
  return {
    localTime,
    utcTime,
    formatTime,
    formatTimeHasDay,
    getThreeDaysLaterFormatted,
  };
}
